<?php
# =====================================
# 作者：老曹  QQ:1484743
# 版权声明：本程序为个人原创、开源程序，禁止用于任何违法用途，任何违法用途均与作者无关。
# 仅限学习交流，转载请注明出处。如需商用请联系作者。
# =====================================
require_once __DIR__ . '/../core/db.php';
header('Content-Type: application/json');
$db = new DB();
$result = [];
$res = $db->query('SELECT host_id, name, ip, os FROM hosts');
while ($row = $res->fetch_assoc()) {
    // 查询该主机下所有硬盘及其最新健康分数和状态
    $disks = [];
    $sql = "SELECT d.device, d.model, d.serial, h.score, h.status, h.assess_time FROM disks d
            LEFT JOIN health_assessments h ON d.disk_id = h.disk_id
            WHERE d.host_id = {$row['host_id']}
            ORDER BY h.assess_time DESC";
    $diskRes = $db->query($sql);
    $diskMap = [];
    $last_report_time = null;
    while ($disk = $diskRes->fetch_assoc()) {
        // 只保留每块硬盘最新一条健康评估
        $key = $disk['device'] . '|' . $disk['serial'];
        if (!isset($diskMap[$key])) {
            $diskMap[$key] = [
                'device' => $disk['device'],
                'model' => $disk['model'],
                'serial' => $disk['serial'],
                'score' => $disk['score'],
                'status' => $disk['status'],
                'assess_time' => $disk['assess_time']
            ];
            // 记录最新上报时间
            if ($disk['assess_time'] && ($last_report_time === null || $disk['assess_time'] > $last_report_time)) {
                $last_report_time = $disk['assess_time'];
            }
        }
    }
    $disks = array_values($diskMap);
    $row['disks'] = $disks;
    $row['last_report_time'] = $last_report_time;
    $result[] = $row;
}
echo json_encode($result);
$db->close(); 